package com.example.demo.pojo;

import com.example.demo.pojo.entity.QuestionLabel;
import com.sun.source.tree.Tree;
import lombok.Getter;

import java.util.*;

/**
 * @author 21172
 */
@Getter
public class TreeQuestionLabel {


    QuestionLabel questionLabel;
    List<TreeQuestionLabel> children;

    @Override
    public String toString() {
        int numberOfTimes = questionLabel.getLevel()*4;
        String repeatedString = " ".repeat(numberOfTimes);
       return repeatedString+"Name: "+questionLabel.getName()+" level: "+questionLabel.getLevel();
    }

    public TreeQuestionLabel() {
        children=new ArrayList<>();
    }

    public void initQuestion(QuestionLabel questionLabel){
        this.questionLabel = questionLabel;
    }
    public void addChild(TreeQuestionLabel child) {
        if (child != null) {
            this.children.add(child);
        }
    }
    // 层序遍历方法
    public void levelOrderTraversal() {
        if (this.children == null || this.children.isEmpty()) {
            return;
        }

        Queue<TreeQuestionLabel> queue = new LinkedList<>();
        queue.add(this); // 从根节点开始

        while (!queue.isEmpty()) {
            TreeQuestionLabel current = queue.poll();
            System.out.println(current); // 访问当前节点

            // 将当前节点的所有子节点添加到队列中
            for (TreeQuestionLabel child : current.children) {
                queue.add(child);
            }
        }
    }
    //    根据id查找节点(并非递归函数)
    public TreeQuestionLabel findTreeQuestionLabelById(Integer id){
        if(id==this.questionLabel.getId()){
            return this;
        }
        if (this.children == null || this.children.isEmpty()) {
            return null;
        }
        Queue<TreeQuestionLabel> queue = new LinkedList<>();
        queue.add(this); // 从根节点开始

        while (!queue.isEmpty()) {
            TreeQuestionLabel current = queue.poll();
            if(current.questionLabel.getId()==id){
                return current;
            }
            // 将当前节点的所有子节点添加到队列中
            for (TreeQuestionLabel child : current.children) {
                queue.add(child);
            }
        }
        return null;
    }
}
